<?php
/**
 * Created by PhpStorm.
 * User: beijingwhg
 * Date: 2017/5/8
 * Time: 下午4:07
 */

namespace App\Listeners\Admin\Auth;


use App\Events\Admin\Auth\Lockout;
use App\Models\AdminLogModel;
use App\Models\AdminModel;

class LockoutListener
{
    protected $admin;

    protected $log;


    public function __construct(AdminModel $adminModel, AdminLogModel $logModel)
    {
        $this->admin = $adminModel;

        $this->log = $logModel;
    }

    public function handle(Lockout $event)
    {
        $report = '用户[%s]尝试登录次数超过%s次未成功,已被限定登录!';

        $username = e($event->request->input('username'));

        $clientIp = $event->request->getClientIp();

        $where = ['phone'=>$username];

        if (strpos($username, '@')) {
            $where = ['email'=>$username];
        }

        $manager = $this->admin->where($where)->first();

        if (!$manager) {
            return false;
        }

        $this->admin->where('admin_id', $manager->admin_id)->update(['status'=>0]);

        $target = $manager->realname ?: $username;

        $report = sprintf($report, $target, config('self.max-attempts'));

        $this->log->create([
            'player' => 'system',
            'type'   => '1',
            'target' => $target,
            'target_id'=> $manager->admin_id,
            'client_ip'=> $clientIp,
            'description'=>$report,
        ]);
    }
}